package com.taofuxn.admin.api.interceptors;

import com.alibaba.fastjson.JSON;
import com.taofuxn.admin.api.config.CurrentUser;
import com.taofuxn.admin.api.model.SysUserModel;
import com.taofuxn.admin.api.service.SessionService;
import com.taofuxn.admin.common.model.BaseResults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import com.taofuxn.admin.api.service.SessionService;


/**
 * 拦截器，登录检查
 */
@Slf4j
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private SessionService sessionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod && ((HandlerMethod) handler).getMethodAnnotation(NoRequestLogin.class) != null) {
            return true;
        }

        SysUserModel user = null;
        Object sessionObj = request.getSession().getAttribute(sessionService.USER_SESSION_KEY);
        if (null == sessionObj) {
            String token = request.getHeader("token");
            if (!StringUtils.isEmpty(token)) {
                user = sessionService.getUserSession(token);
            }
        } else {
            user = (SysUserModel) sessionObj;
        }

        if (user == null) {
            CurrentUser.remove();
            response.setHeader("content-type", "application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(BaseResults.toLogin()));
            return false;
        }

        CurrentUser.set(user);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUser.remove();
    }
}
